Comparative Maps: Life Expectancy (1967 vs 2007)

world <- spData::world

world_gap <- world %>%
  left_join(
    gapminder %>%
      filter(year %in% c(1967, 2007)) %>%
      select(country, year, lifeExp) %>%
      tidyr::pivot_wider(names_from = year, values_from = lifeExp),
    by = c("name_long" = "country")
  ) %>%
  mutate(delta = `2007` - `1967`)
vals <- c(world_gap$`1967`, world_gap$`2007`)
brks <- classInt::classIntervals(vals, n = 7, style = "quantile")$brks

m1 <- tm_shape(world_gap) +
  tm_polygons("1967", palette = "Blues", title = "Life Expectancy 1967", breaks = brks) +
  tm_layout(frame = TRUE)

m2 <- tm_shape(world_gap) +
  tm_polygons("2007", palette = "Blues", title = "Life Expectancy 2007", breaks = brks) +
  tm_layout(frame = TRUE)

tmap_arrange(m1, m2, ncol = 2)

tm_shape(world_gap) +
  tm_polygons("delta", palette = "RdBu", midpoint = 0,
              title = "Change in Life Expectancy (2007 - 1967)") +
  tm_layout(legend.outside = TRUE)

Interactive Life Expectancy graph

world_time <- world %>%
  left_join(
    gapminder %>% select(country, year, lifeExp),
    by = c("name_long" = "country")
  )


library(leaflet)

years_to_plot <- c(1967, 1987, 1997, 2007)

map <- leaflet() %>% addTiles()

for (yr in years_to_plot) {
  map <- map %>%
    addPolygons(
      data = subset(world_time, year == yr),
      fillColor = ~colorNumeric("YlOrRd", lifeExp.y)(lifeExp.y),
      fillOpacity = 0.7, color = "white", weight = 0.5,
      group = as.character(yr),
      popup = ~paste0("<b>", name_long, "</b><br>",
                      "Year: ", yr, "<br>",
                      "Life Expectancy: ", round(lifeExp.y, 1))
    )
}

map <- map %>%
  addLayersControl(
    overlayGroups = as.character(years_to_plot),
    options = layersControlOptions(collapsed = FALSE)
  )

map
tmap_arrange(m1, m2, ncol = 2)

colnames(world_time)
##  [1] "iso_a2"    "name_long" "continent" "region_un" "subregion" "type"     
##  [7] "area_km2"  "pop"       "lifeExp.x" "gdpPercap" "geom"      "year"     
## [13] "lifeExp.y"
map_facets <- tm_shape(world_time) +
  tm_polygons("lifeExp.y", palette = "YlGnBu", title = "Life Expectancy") +
  tm_facets(by = "year", ncol = 2) +
  tm_layout(legend.outside = TRUE)

map_facets

library(tmap)

if (!dir.exists("figlife")) dir.create("figlife")

for (yr in sort(unique(world_time$year))) {
  map <- tm_shape(subset(world_time, year == yr)) +
    tm_polygons("lifeExp.y", palette = "YlGnBu", title = "Life Expectancy") +
    tm_layout(
      legend.outside = TRUE,
      main.title = paste("Life Expectancy -", yr),
      main.title.size = 1.5
    )
  
  out_file <- file.path("figlife", paste0("lifeExp_", yr, ".png"))
  
  png(out_file, width = 1000, height = 700)
  print(map)   
  dev.off()
  message("Saved: ", normalizePath(out_file))
}

HIV vs Gapminder Dataset

hiv_data_raw <- WDI(
  indicator = "SH.DYN.AIDS.ZS",
  start = 1990,
  end = 2020,
  extra = TRUE
)

# Clean and prepare HIV data
hiv_data <- hiv_data_raw %>%
  rename(hiv_prevalence = SH.DYN.AIDS.ZS) %>%
  filter(!is.na(hiv_prevalence)) %>%
  mutate(
    continent = case_when(
      region %in% c("Sub-Saharan Africa (all income levels)", 
                    "Sub-Saharan Africa") ~ "Africa",
      region %in% c("East Asia & Pacific", "South Asia") ~ "Asia",
      region %in% c("Europe & Central Asia") ~ "Europe",
      region %in% c("Latin America & Caribbean") ~ "Americas",
      region %in% c("Middle East & North Africa") ~ "Africa",
      TRUE ~ "Other"
    )
  ) %>%
  select(country, iso3c, year, hiv_prevalence, continent, region, income)
library(sf)
library(dplyr)
library(tidyr)
library(tmap)
library(countrycode)
library(spData)

# Load world data
world <- spData::world
world$iso_a3 <- countrycode(world$iso_a2, "iso2c", "iso3c")

# Prepare HIV data for mapping (1990, 2000, 2005)
hiv_map_data <- hiv_data %>%
  filter(year %in% c(1990, 2000, 2005)) %>%
  select(iso3c, year, hiv_prevalence)

# Join with world geometry
world_hiv <- left_join(world, hiv_map_data, by = c("iso_a3" = "iso3c"))

# Pivot wider for delta computation
hiv_delta <- hiv_map_data %>%
  pivot_wider(
    names_from = year,
    values_from = hiv_prevalence,
    names_prefix = "year_"
  ) %>%
  mutate(
    delta_2000_1990 = year_2000 - year_1990,
    delta_2005_2000 = year_2005 - year_2000
  )

# Join deltas back with geometry
world_hiv_delta <- left_join(world, hiv_delta, by = c("iso_a3" = "iso3c"))

# Define breaks
hiv_vals <- world_hiv$hiv_prevalence[!is.na(world_hiv$hiv_prevalence)]
hiv_brks <- c(0, 0.1, 0.5, 1, 5, 10, 20, max(hiv_vals, na.rm = TRUE))
delta_brks <- c(-10, -5, -2, 0, 2, 5, 10, 20)

# ---- Visualization ----
tmap_mode("plot")

# Main year maps
m1990 <- tm_shape(world_hiv %>% filter(year == 1990)) +
  tm_polygons("hiv_prevalence",
              palette = "YlOrRd",
              breaks = hiv_brks,
              title = "HIV Prevalence (%)") +
  tm_layout(main.title = "Year 1990", main.title.size = 1.2, frame = FALSE)

m2000 <- tm_shape(world_hiv %>% filter(year == 2000)) +
  tm_polygons("hiv_prevalence",
              palette = "YlOrRd",
              breaks = hiv_brks,
              title = "HIV Prevalence (%)") +
  tm_layout(main.title = "Year 2000", main.title.size = 1.2, frame = FALSE)

m2005 <- tm_shape(world_hiv %>% filter(year == 2005)) +
  tm_polygons("hiv_prevalence",
              palette = "YlOrRd",
              breaks = hiv_brks,
              title = "HIV Prevalence (%)") +
  tm_layout(main.title = "Year 2005", main.title.size = 1.2, frame = FALSE)

# Delta maps
m_delta1 <- tm_shape(world_hiv_delta) +
  tm_polygons("delta_2000_1990",
              palette = "-RdYlGn",
              breaks = delta_brks,
              title = "Δ HIV (2000 - 1990)") +
  tm_layout(main.title = "Change (2000–1990)", main.title.size = 1.2, frame = FALSE)

m_delta2 <- tm_shape(world_hiv_delta) +
  tm_polygons("delta_2005_2000",
              palette = "-RdYlGn",
              breaks = delta_brks,
              title = "Δ HIV (2005 - 2000)") +
  tm_layout(main.title = "Change (2005–2000)", main.title.size = 1.2, frame = FALSE)

# Arrange maps
tmap_arrange(m1990, m2000, m2005, m_delta1, m_delta2, ncol = 3)

library(sf)
library(dplyr)
library(tidyr)
library(tmap)
library(countrycode)
library(spData)

world <- spData::world
world$iso_a3 <- countrycode(world$iso_a2, "iso2c", "iso3c")

hiv_map_data <- hiv_data %>%
  filter(year %in% c(1990, 2000)) %>%
  select(iso3c, year, hiv_prevalence)

world_hiv <- left_join(world, hiv_map_data, by = c("iso_a3" = "iso3c"))

hiv_delta <- hiv_map_data %>%
  pivot_wider(
    names_from = year,
    values_from = hiv_prevalence,
    names_prefix = "year_"
  ) %>%
  mutate(
    delta_2000_1990 = year_2000 - year_1990
  )

# Join deltas back with geometry
world_hiv_delta <- left_join(world, hiv_delta, by = c("iso_a3" = "iso3c"))

# Define breaks
hiv_vals <- world_hiv$hiv_prevalence[!is.na(world_hiv$hiv_prevalence)]
hiv_brks <- c(0, 0.1, 0.5, 1, 5, 10, 20, max(hiv_vals, na.rm = TRUE))
delta_brks <- c(-10, -5, -2, 0, 2, 5, 10, 20)

# ---- Visualization ----
tmap_mode("plot")

# Main year maps
m1990 <- tm_shape(world_hiv %>% filter(year == 1990)) +
  tm_polygons("hiv_prevalence",
              palette = "YlOrRd",
              breaks = hiv_brks,
              title = "HIV Prevalence (%)") +
  tm_layout(main.title = "Year 1990", main.title.size = 1.2, frame = FALSE)

m2000 <- tm_shape(world_hiv %>% filter(year == 2000)) +
  tm_polygons("hiv_prevalence",
              palette = "YlOrRd",
              breaks = hiv_brks,
              title = "HIV Prevalence (%)") +
  tm_layout(main.title = "Year 2000", main.title.size = 1.2, frame = FALSE)

# Delta map
m_delta <- tm_shape(world_hiv_delta) +
  tm_polygons("delta_2000_1990",
              palette = "-RdYlGn",
              breaks = delta_brks,
              title = "Delta HIV (%)") +
  tm_layout(main.title = "Change in HIV (2000-1990)", main.title.size = 1.2, frame = FALSE)

# Arrange maps: 3 maps in a row
tmap_arrange(m1990, m2000, ncol = 2)

m_delta

library(gapminder)
library(dplyr)
library(tmap)
library(countrycode)
library(spData)

# Prepare Gapminder data for 1990 and 2000 (nearest available: 1992 & 2002)
gap_age <- gapminder %>%
  filter(year %in% c(1992, 2002)) %>%
  mutate(iso3c = countrycode(country, "country.name", "iso3c")) %>%
  group_by(iso3c, year) %>%
  summarise(avg_lifeExp = mean(lifeExp, na.rm = TRUE), .groups = "drop")

# Join with world geometry
world_age <- left_join(world, gap_age, by = c("iso_a3" = "iso3c"))

# Compute delta
age_delta <- gap_age %>%
  pivot_wider(names_from = year, values_from = avg_lifeExp, names_prefix = "year_") %>%
  mutate(delta_2002_1992 = year_2002 - year_1992)

world_age_delta <- left_join(world, age_delta, by = c("iso_a3" = "iso3c"))

# Define breaks for life expectancy
life_brks <- seq(40, 85, by = 5)
delta_brks <- c(-5, -2, 0, 2, 5, 10, 20)

# Visualization
tmap_mode("plot")

m1990_age <- tm_shape(world_age %>% filter(year == 1992)) +
  tm_polygons("avg_lifeExp", palette = "Blues", breaks = life_brks,
              title = "Life Expectancy (Years)") +
  tm_layout(main.title = "Average Life Expectancy (1992)", frame = FALSE)

m2000_age <- tm_shape(world_age %>% filter(year == 2002)) +
  tm_polygons("avg_lifeExp", palette = "Blues", breaks = life_brks,
              title = "Life Expectancy (Years)") +
  tm_layout(main.title = "Average Life Expectancy (2002)", frame = FALSE)

m_age_delta <- tm_shape(world_age_delta) +
  tm_polygons("delta_2002_1992", palette = "-RdYlGn", breaks = delta_brks,
              title = "Change (2002–1992)") +
  tm_layout(main.title = "Change in Life Expectancy", frame = FALSE)

tmap_arrange(m1990_age, m2000_age, ncol = 2)

m_age_delta

# Compute percentage delta instead of absolute difference
age_delta <- gap_age %>%
  pivot_wider(names_from = year, values_from = avg_lifeExp, names_prefix = "year_") %>%
  mutate(
    delta_pct_2002_1992 = ((year_2002 - year_1992) / year_1992) * 100
  )

world_age_delta <- left_join(world, age_delta, by = c("iso_a3" = "iso3c"))

m_age_delta <- tm_shape(world_age_delta) +
  tm_polygons("delta_pct_2002_1992",
              palette = "-RdYlGn",
              breaks = c(-10, -5, 0, 5, 10, 20, 40),
              title = "Delta Life Exp.(%)") +
  tm_layout(
    main.title = "Change in Life Expectancy (2002–1992, %)",
    main.title.size = 1.2,
    frame = FALSE,
    legend.outside = TRUE,                 # place legend outside the map
    legend.outside.position = "right",     # position on the right
    legend.title.size = 0.8,               # smaller title
    legend.text.size = 0.6,                # smaller text
    legend.bg.color = "white",             # white background
    legend.bg.alpha = 0.6,                 # semi-transparent
    outer.margins = c(0, 0.2, 0, 0)        # add space on the right for legend
  )

m_age_delta